const { v4: uuidv4 } = require('uuid');
const getTime = require('../utils/getTime');
const { executeQuery } = require('../utils/dataAccess');

// 获取菜单
exports.getRouters = async (req, res, next) => {

    try {

        let user_id = req.auth.user_id;
        let role_id = [];  // 定义角色id数组
        let menuids = [];  // 
        let roles_menu = [];

        async function getRoles(){
            let sql = `SELECT role_id FROM sys_user_role WHERE user_id = '${user_id}';`;

            try {  
                const result = await executeQuery(sql);
                let roles = result.rows
                role_id = roles.map(role => role.role_id);  // 获取角色id数组
            } catch (err) {  
                next(err); // 如果发生错误，抛出异常  
            } 
        }

        async function getMenuIds(){
            let sql = `SELECT * FROM sys_role_menu where role_id = '${role_id[0]}'`;
            try {
                const result = await executeQuery(sql);  // 获取角色菜单权限信息
                menuids = result.rows;  // 获取角色菜单权限信息数组

                menuids.forEach(element => {
                    roles_menu.push(element.menu_id);  // 获取角色菜单权限信息数组
                });
                
            } catch (err) {
                next(err);  // 如果发生错误，抛出异常
            }
        }

        await getRoles()
        await getMenuIds()
  
        let sql = `SELECT * FROM sys_menu`;  
  
    
        const result = await executeQuery(sql); // 执行查询语句  
        let menuList = result.rows; // 获取查询结果 

        if(role_id[0] != '1'){ // 如果是超级管理员，则不进行过滤
            menuList = menuList.filter(item => roles_menu.includes(item.menu_id)); // 过滤出用户有权限的菜单列表数据
        }


        let newList = menuList.filter(item => {
            return item.parent_id == 0;
        });

        newList.forEach(item => {  
            item.children = menuList.filter(child => child.parent_id == item.menu_id);
        })

        let sendMenuList = []

        newList.forEach(item => {
          sendMenuList.push({
            alwaysShow: false,
            children: menuChildren(item.children),
            component: 'Layout',
            hidden: item.visible == '1' ? true : false,
            menuType: item.menu_type,
            name: titleCase5(item.path),
            path:'/' + item.path,
            redirect: 'noRedirect',
            parent_id: item.parent_id,
            id: item.menu_id,
            meta: { 
                title: item.menu_name, 
                icon: item.icon, 
                link: null,
                noCache: false 
            },
          }) 
        })

        

        
        function titleCase5(str) {
            return str.toLowerCase().replace(/( |^)[a-z]/g, (L) => L.toUpperCase());
        }

        function menuChildren(item) {
          let newChildren = []
          if(item.length> 0){
            item.forEach(item => {
              newChildren.push({
                component: item.component,
                hidden: item.visible == '1' ? true : false,
                name: titleCase5(item.path),
                path: item.path,
                meta: {
                    title: item.menu_name, 
                    icon: item.icon, 
                    link: null,
                    noCache: false 
                }
              })
            })
          }else{
            newChildren = []
          }
          return newChildren
        }

        
  
        // 返回树形结构的菜单给前端  
        res.json({code: 200, message: '查询成功', data: sendMenuList});  
    } 
    catch (err) {  
        // 捕获错误并返回给前端  
        next(err); 
    }  
}

exports.getMenuList = async (req, res, next) => {
    
    let sqlCon = ` where 1=1 `

    if(req.body.menuName){sqlCon += ` and menu_name like '%${req.body.menuName}%'`}
    if(req.body.status){sqlCon += ` and status = '${req.body.status}'`}

    let sql = `SELECT 
        menu_id as menuId,
        parent_id as parentId,
        component as component,
        create_by as createBy,
        create_time as createTime,
        icon as icon,
        is_cache as isCache,
        is_frame as isFrame,
        menu_name as menuName,
        menu_type as menuType,
        order_num as orderNum,
        path as path,
        perms as perms,
        remark as remark,
        status as status,
        update_by as updateBy,
        update_time as updateTime,
        visible as visible
        FROM sys_menu`;

    try {
        sql += sqlCon + ` order by order_num`; // 添加排序条件，可以根据需要进行修改
        let result = await executeQuery(sql);
        let menuList = result.rows; // 获取菜单列表数据
        res.json({
            code: 200, 
            msg: '查询成功', 
            data: menuList
        });

    }
    catch (err) {
        next(err)
    }
}


exports.updatedMenu = async (req, res, next) => {
    let sqlStatement;  
    let requestParams;  
  
    // 生成或获取 menuId  
    let menuId = req.body.menuId === 'newid' ? uuidv4() : req.body.menuId;  
  
    const { parentId, component, icon, isCache, isFrame, menuName, menuType, orderNum, path, perms, remark, status, visible } = req.body;  
  
    // 如果是新记录，则插入；否则，更新现有记录  
    if (req.body.menuId === 'newid') {  
        const createTime = getTime(); // 假设 getTime() 是获取当前时间的函数  
        const createBy = req.auth.user_name;  
  
        sqlStatement = `INSERT INTO sys_menu (parent_id, component, create_by, create_time, icon, is_cache, is_frame, menu_name, menu_type, order_num, path, perms, remark, status, visible) VALUES ('${parentId}', '${component}', '${createBy}', '${createTime}', '${icon}', '${isCache}', '${isFrame}', '${menuName}', '${menuType}', '${orderNum}', '${path}', '${perms}', '${remark}', '${status}', '${visible}')`;  
    } else {  
        const updateTime = getTime(); // 假设 getTime() 是获取当前时间的函数  
        const updateBy = req.auth.user_name;  
  
        sqlStatement = `UPDATE sys_menu SET parent_id= '${parentId}', component= '${component}', icon= '${icon}', is_cache= '${isCache}', is_frame= '${isFrame}', menu_name= '${menuName}', menu_type= '${menuType}', order_num= '${orderNum}', path= '${path}', perms= '${perms}', remark= '${remark}', status= '${status}', update_by= '${updateBy}', update_time= '${updateTime}', visible= '${visible}' WHERE menu_id =  '${menuId}'`; 
    }  
  
    try {
        // 执行查询  
        const result = await executeQuery(sqlStatement);  
  
        res.json({  
            code: 200,  
            message: '查询成功',  
            data: result.rows // 返回插入或更新的记录（如果有的话）  
        });
    } 
    catch (error) {
        next(error);
    }
}

exports.deleteMenu = async (req, res, next) => {  
    try { 
        const { menuIds } = req.body;   
  
        if (!menuIds || menuIds.length === 0) {  
            throw new Error('请选择要删除的菜单');
        }  
    
        // 将menuIds数组转换为适合SQL语句的字符串格式  
        const idsString = menuIds.map(id => `'${id}'`).join(',');  
    
        const sqlStatement = `DELETE FROM sys_menu WHERE menu_id IN (${idsString})`;
        const sqlStatement2 = `DELETE FROM sys_role_menu WHERE menu_id IN (${idsString})`;

        const result = await executeQuery(sqlStatement);
        const result2 = await executeQuery(sqlStatement2);
  
        res.json({  
            code: 200,  
            message: 'Success',  
            data: {
                result: result,
                result2: result2
            }
        });  
    } catch (error) {  
        next(error)
    }  
};

